package com.situ.company.util;


import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;
 
public class FmtRequest {
	
	/**
	 * 根据请求的参数情况反射得到实体类的对象（请求的参数名与实体类的属性名一致,一个参数名对应一个参数值）
	 * @param <T>
	 * @param req
	 * @param clazz
	 * @return
	 */
	
	public static <T> T parseModel(HttpServletRequest req,Class<T> clazz){
		T obj = null;
		
		try {
			obj = clazz.newInstance();
		} catch (InstantiationException |IllegalAccessException e) {			
			e.printStackTrace();
			return null;
		} 
		 Map<String,String[]> map = req.getParameterMap();
		for(Entry<String, String[]> entry:map.entrySet()) {
			String name = entry.getKey();
			if("action".equals(name))
				continue;
			try {
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);
				field.set(obj, entry.getValue()[0]);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	
	/**
	 * 根据映射关系反射得到实体类的对象
	 * @param <T>
	 * @param req
	 * @param clazz
	 * @param fields
	 * @return
	 */
	public static <T> T parseModel(HttpServletRequest req,Class<T> clazz,Map<String,String> fields) {
T obj = null;
		
		try {
			obj = clazz.newInstance();
		} catch (InstantiationException |IllegalAccessException e) {			
			e.printStackTrace();
			return null;
		} 
		 Map<String,String[]> map = req.getParameterMap();
		for(Entry<String, String> entry:fields.entrySet()) {
			String name = entry.getKey();
			String val = req.getParameter(entry.getValue());
			
			try {
				Field field = clazz.getDeclaredField(name);
				field.setAccessible(true);
				field.set(obj, val);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}
	
	public static void write(Writer wr,Object val) {
		
		if(val instanceof Collection<?>) {
			write(wr,new JSONArray((Collection<?>) val).toString());
			
		}else if (val instanceof String) {
			write(wr,val.toString());
		}else if (val instanceof Map<?,?>) {
			write(wr,new JSONObject((Map<?,?>) val).toString());
		}else {  
			write(wr,new JSONObject(val).toString());
		}
	}
	
	
	public static void write(Writer wr,String val) {
		try {
			wr.write(val);
			wr.flush();
			wr.close(); 
		} catch (Exception e) {
			
		}
		
		wr = null;
	}


//	public static void write(PrintWriter writer, int val) {
//		try {
//			writer.write(val);
//			writer.flush();
//			writer.close(); 
//		} catch (Exception e) {
//			
//		}
//		
//		writer = null;
//		
//	}
}
